package controller;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;

import model.Course;
import model.Student;
import model.StudentCourse;
import model.Teacher;

/**
 * Created by BaiYunfei on 2017/6/14.
 */
public class SelectCourseController extends BaseController {
	
    public void list(){
    	SqlPara sqlPara = null;
    	int role = getRole();
    	if(role == 3){
    		sqlPara = Db.getSqlPara("listSC");
    	}else if(role ==2){
    		Teacher teacher = Teacher.dao.findByUserId(getUserId());
    		sqlPara = Db.getSqlPara("listSCByTeacher", teacher.getStr("Teacher_ID"));
    	}else if(role ==1){
    		Student student = Student.dao.findByUserId(getUserId());
    		sqlPara = Db.getSqlPara("listSelected", student.getStr("Student_ID"));
    	}
        Page<Record> scPage = Db.paginate(
        		getPageNumber(),
        		getPageSize(),
        		sqlPara);
        renderDataTable(scPage);
    }

    @Before(Tx.class)
    public void save(){
        StudentCourse sc = StudentCourse.dao.findFirst(Db.getSqlPara("getSCById",getPara("Course_ID"),getPara("Student_ID")));
        if(sc!=null){
        	sc.set("Grade", getParaToInt("Grade"));
        	sc.update();
        	setAttr("status","success");
        }
        renderJson();
    }
    
    public void select(){
    	Student student = Student.dao.findByUserId(getUserId());
    	StudentCourse sc = new StudentCourse();
    	sc.set("Course_ID", getPara("Course_ID"));
    	sc.set("Student_ID", student.getStr("Student_ID"));
    	sc.save();
    	renderJson();
    }
    
    public void remove(){
    	String id = getPara("id");
    	Course.dao.deleteById(id);
    	renderJson();
    }
    
    public void addPage(){
    	Record record = Db.findFirst(Db.getSqlPara("getSCVoById", getPara("Course_ID"),getPara("Student_ID")));
    	setAttr("sc",record);
        render("sc-add.html");
    }

    public void index(){
        render("sc-list.html");
    }
	
}
